<script setup lang="ts">
defineOptions({
  name: "ALL_FAB_OVERVIEW"
});

import { ref, markRaw, watch, computed, provide, nextTick, onMounted, toRefs } from "vue";
import { useRoute } from "vue-router";
import { ArrowLeft, ArrowRight, Rollback } from "@px-ui/icons-vue";
import switchTableTabs from "../../components/switchTableTabs/index.vue";
import board from "../components/board/index.vue";
import list from "../components/list/index.vue";
import topology from "../components/topology/index.vue";
import abnormalInfo from "@/views/common/fab/detail/components/baseInfo/components/abnormalInfo.vue";
import { type OptionsType } from "@/components/ReSegmented";
import { emitter } from "@/utils/mitt";
import { useElementBounding } from "@vueuse/core";
import { type SubjectType } from "@/utils/types";
import { subjectModules } from "@/utils/constant";
import { useRouterStoreHook } from "@/store/modules/router";
import { getFabAreaSelectOptions, getFabBoardConfigSelectOptions } from "@/api/modules/fab";

const route = useRoute();
const routerStore = useRouterStoreHook();

const boardProps = ref<Record<string, any>>({
  area: "",
  reset: false
});

const listProps = ref<Record<string, any>>({
  eqpStatus: "",
  className: "",
  area: "",
  isWarning: null
});

const switchTabsOptions = computed(() => [
  {
    label: "看板",
    com: markRaw(board),
    props: toRefs(boardProps.value)
  },
  {
    label: "机台列表",
    com: markRaw(list),
    props: toRefs(listProps.value)
  }
]);

const overviewRef = ref<HTMLElement | null>(null);
const switchTableTabsRef = ref<InstanceType<typeof switchTableTabs> | null>(null);
const activeTab = ref<number>(0);
// 报警列表 是否打开
const isDrawerOpen = ref<boolean>(true);
const { height } = useElementBounding(overviewRef);
const subject = ref<SubjectType>("MACHINE");
const abnormalInfoKey = ref<string>(Math.random().toString(36).slice(2, 10));
const areas = ref<Record<string, any>>({
  workbench: "",
  machine: "",
  electrictity: "",
  water: "",
  gas: ""
});

provide("subject", subject);

const abnormal_info_height = computed(() => {
  return `${height.value - 40 - 16 - 54 - 16 - 16}px`;
});

const height_value = computed(() => {
  return `${height.value - 164 - 40 - 16 - 54 - 16 - 16}px`;
});

const subjectOptions = computed(() => subjectModules.slice(1));
const isShowArrow = computed(() => activeTab.value === 1);
const isShowAbnormalInfo = computed(() => activeTab.value === 1 && isDrawerOpen.value);

const isShowRollback = ref<boolean>(false);
const classLabel = ref<string>("");
const isSkip = ref<boolean>(false);

const toggleDrawerHandler = () => {
  isDrawerOpen.value = !isDrawerOpen.value;
};

const subjectChangeHandler = async () => {
  abnormalInfoKey.value = Math.random().toString(36).slice(2, 10);
  setViceMenus();
  await nextTick();
  switchTableTabsRef.value.updateCurrentTab();
};

/**
 * @description: 看板中事件回调
 * @param {*} type 触发的主体    eqpStatus 今日机台状态统计
 * @param {*} data 返回的数据
 * @return {*}
 */
const emitBoardEvent = async (type: string, data: any) => {
  switch (type) {
    case "eqpStatus":
    case "pmTask":
    case "repairTask":
    case "abnormalAlarm":
      await skipToFabList(type, data);
      break;
  }
};

provide("emitBoardEvent", emitBoardEvent);

/**
 * @description: 看板中区域选择下拉框选择事件回调
 * @param {*} type 触发的主体    workbench  机台信息
 * @param {*} data 返回的数据
 * @return {*}
 */
const emitBoardAreaEvent = async (type: string, area: string) => {
  areas.value[type] = area;
  listProps.value.area = area === "ALL" ? "" : area;
};

provide("emitBoardAreaEvent", emitBoardAreaEvent);

/**
 * @description: 看板中区域选择下拉框选择事件回调
 * @param {*} classCode
 * @param {*} className
 * @return {*}
 */
const emitBoardClassEvent = async (classCode?: string, className?: string) => {
  listProps.value.className = classCode;
  boardProps.value.reset = false;
  classLabel.value = className;
  isShowRollback.value = true;
};

provide("emitBoardClassEvent", emitBoardClassEvent);

const showAllData = () => {
  classLabel.value = "";
  boardProps.value.reset = true;
};

provide("showAllData", showAllData);

const skipToFabList = async (type: string, data: any) => {
  isSkip.value = true;
  listProps.value.eqpStatus = "";
  listProps.value.isWarning = null;
  switch (type) {
    case "eqpStatus":
      listProps.value.eqpStatus = data.eqpStatus;
      await nextTick();
      activeTab.value = 1;
      break;
    case "pmTask":
    case "repairTask":
      listProps.value.eqpStatus = "PM";
      await nextTick();
      activeTab.value = 1;
      break;
    case "abnormalAlarm":
      listProps.value.isWarning = true;
      await nextTick();
      activeTab.value = 1;
      break;
  }
};

const formatListProps = () => {
  if (!isSkip.value) {
    listProps.value.eqpStatus = "";
    listProps.value.className = "";
    listProps.value.area = "";
    listProps.value.isWarning = null;
  }
};

const setViceMenus = () => {
  if (routerStore.subject === "ALL") {
    emitter.emit("showViceMenusChange", activeTab.value === 1 && subject.value === "GAS");
  } else {
    // 其他科目没有副路由
    emitter.emit("showViceMenusChange", false);
  }
};

const getRouterParams = async () => {
  // isWarning   false    true
  const {
    query: { tab = "0", eqpStatus = "", className = "", area = "", isWarning = "" }
  } = route;
  switch (tab) {
    case "0":
      break;
    case "1":
      eqpStatus && (listProps.value.eqpStatus = eqpStatus);
      className && (listProps.value.className = className);
      area && (listProps.value.area = area);
      switch (isWarning) {
        case "false":
          listProps.value.isWarning = false;
          break;
        case "true":
          listProps.value.isWarning = true;
          break;
        default:
          listProps.value.isWarning = null;
          break;
      }
      break;
    default:
      break;
  }
  await nextTick();
  activeTab.value = Number(tab);
};

const areaOptions = ref<Array<any>>([]);
provide("areaOptions", areaOptions);

const queryAreaOptionsFn = async () => {
  const res = await getFabAreaSelectOptions(null);
  areaOptions.value = res
    ?.map(({ areaId: value = "", areaCode: label = "" }: any) => ({ value, label }))
    ?.filter(({ value, label }) => !!value && !!label);
  areaOptions.value.unshift({ value: "ALL", label: "全部区域" });
  boardProps.value.area = areaOptions.value[0]?.value;
};

const beforeChangeHandler = () => {
  formatListProps();
};

onMounted(async () => {
  await getRouterParams();
  if (activeTab.value === 0) {
    await queryAreaOptionsFn();
  }
});

/**
 * 监听选中值的变化，状态改变时触发 showViceMenusChange 事件
 */
watch(
  () => activeTab.value,
  val => {
    setViceMenus();
    switch (val) {
      case 0:
        isSkip.value = false;
        listProps.value.eqpStatus = "";
        listProps.value.className = "";
        listProps.value.area = "";
        listProps.value.isWarning = null;
        break;
      case 1:
        boardProps.value.area = "ALL";
        boardProps.value.reset = false;
        isShowRollback.value = false;
        classLabel.value = "";
        break;
      default:
        break;
    }
  },
  { immediate: true, deep: true }
);
</script>

<template>
  <div ref="overviewRef" class="overview">
    <switchTableTabs
      ref="switchTableTabsRef"
      v-model="activeTab"
      :boxShadow="false"
      :options="switchTabsOptions"
      @before-change="beforeChangeHandler"
    >
      <transition name="overview-left-drawer-btn" mode="out-in">
        <template v-if="activeTab === 0" #default>
          <div class="model-box-slot-title">
            <div v-if="isShowRollback && classLabel" style="display: flex; align-items: center">
              <span style="font-size: 13px; line-height: 1; color: #555">{{ classLabel }}</span>
              <px-tooltip content="全部科室数据">
                <px-button type="primary" plain text size="large" :icon="Rollback" @click="showAllData" />
              </px-tooltip>
            </div>

            <px-select v-model="boardProps.area" style="width: 120px" size="small" placeholder="请选择区域">
              <px-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </div>
        </template>
      </transition>

      <!-- fab中去掉拓扑图模块  产品同步 2024-12-18 -->
      <!-- <transition name="overview-switch-right-btn" mode="out-in">
        <px-select v-if="activeTab === 1" v-model="subject" style="width: 120px" @change="subjectChangeHandler">
          <px-option v-for="item in subjectOptions" :key="item.subject" :label="item.label" :value="item.subject" />
        </px-select>
      </transition> -->
    </switchTableTabs>
    <!-- fab中去掉拓扑图模块  产品同步 2024-12-18 -->
    <!-- <transition name="overview-left-drawer-btn" mode="out-in">
      <div v-if="isShowArrow" class="left-drawer-btn" @click.stop="toggleDrawerHandler">
        <px-icon><ArrowLeft v-if="isDrawerOpen" /><ArrowRight v-else /> </px-icon>
      </div>
    </transition>
    <transition name="overview-left-abnormal-info" mode="out-in">
      <div v-if="isShowAbnormalInfo" class="left-drawer-abnormal-info">
        <abnormalInfo :key="abnormalInfoKey" :height_value="height_value" title="报警列表" isEqpIdSelect />
      </div>
    </transition> -->
  </div>
</template>

<style lang="scss" scoped>
.overview {
  position: relative;
  height: 100%;

  .overview-switch-right-btn-enter-active,
  .overview-switch-right-btn-leave-active {
    transition: all 0.3s ease;
  }

  .overview-switch-right-btn-enter-from {
    opacity: 0;
    transform: translateX(120px);
  }

  .overview-switch-right-btn-leave-to {
    opacity: 0;
    transform: translateX(120px);
  }

  .left-drawer-btn {
    position: absolute;
    top: 360px;
    left: -24px;
    z-index: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 20px;
    height: 36px;
    background-color: var(--px-color-primary);
    border-radius: 0 4px 4px 0;

    &:hover {
      cursor: pointer;
    }

    .px-icon {
      font-size: 24px;
      font-weight: 600;
      line-height: 1;
      color: #fff;
    }
  }

  .overview-left-drawer-btn-enter-active,
  .overview-left-drawer-btn-leave-active {
    transition: all 0.3s ease;
  }

  .overview-left-drawer-btn-enter-from {
    opacity: 0;
    transform: translateX(16px);
  }

  .overview-left-drawer-btn-leave-to {
    opacity: 0;
    transform: translateX(16px);
  }

  .left-drawer-abnormal-info {
    position: absolute;
    top: 56px;
    left: 0;
    width: 420px;
    height: v-bind(abnormal_info_height);
    border-radius: 4px;
  }

  .overview-left-abnormal-info-enter-active,
  .overview-left-abnormal-info-leave-active {
    transition: all 0.4s ease;
  }

  .overview-left-abnormal-info-enter-from {
    transform: translateX(-500px);
  }

  .overview-left-abnormal-info-leave-to {
    transform: translateX(-500px);
  }

  .model-box-slot-title {
    display: flex;
    gap: 16px;
    align-items: center;
  }
}
</style>
